<?php
$_REQUEST and extract($_REQUEST);
$c = 1;
if(!isset($ac) or empty($ac)) $ac = 'setting';

if ($ac == 'setting') {
	HTML_header();
	HTML_setting_form();
	HTML_footer();
} elseif ($ac == "replace") {
	HTML_header();
	HTML_back();
	batch_replace($path, $search, $replace);
	HTML_footer();
}

function p($s){
	echo '<pre>';
	print_r($s);
	echo '</pre>';
}

function batch_replace($dirname, $find, $replace)
{
	global $c;
	$dir = dir($dirname);
	//列出 images 目录中的文件
	while (($file = $dir->read()) !== false)
	{
		if($file == '.' or $file == '..') continue;
		$file_path = $dirname . '/' . $file;
		if(is_dir($file_path)) batch_replace($file_path, $find, $replace);
		else
		{
			$count = replace_str($file_path, $find, $replace);
			p("filename[" . $c . "]: [" . $file_path . "] 替换 <font color='red'><b>" . $count . "</b></font> 个<br />");
			$c++;
		}
	}
	$dir->close();	
}

function replace_str($file_path, $find, $replace)
{
	$file = file_get_contents($file_path);
	$file = str_replace($find, $replace, $file, $c);
	file_put_contents($file_path, $file);
	return $c;
}

function HTML_header(){
	?>
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
	<html>
	 <head>
	  <title> 文件批量替换工具 </title>
	  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	  <meta name="Generator" content="EditPlus">
	  <meta name="Author" content="">
	  <meta name="Keywords" content="">
	  <meta name="Description" content="">
	  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	 <style>
	 body{font-size:12px;}
	 .main{width:800px;margin:0 auto;}
	 ul li{width:100%;list-style-type:none;}
	 form *{padding:5px; margin:0px 5px;}
	 form textarea{width:100%; height:100px;}
	 form input{margin:0 auto;}
	 .w200{width:200px;}
	 .w400{width:400px;}
	 </style>
	 </head>
	 <body>
	 <div class="main">
	<?php
}

function HTML_footer(){
	?>
	 </div>
	 </body>
	</html>
	<?php
}

function HTML_setting_form(){
	?>
	<form method="post" action="">
		<ul>
		<li>搜索内容</li>
		<li><input type="hidden" name="ac" value="replace"></li>
		<li><textarea name="search" id="search"></textarea></li>
		<li>替换内容</li>
		<li><textarea name="replace" id="replace"></textarea></li>
		<li>选择文件夹</li>
		<li><input type="text" name="path" id="path" value="" class="w400"></li>
		<li><input type="submit" value="提交" onclick=""><input type="reset" value="重设" onclick=""></li>
		</ul>
	</form>
	<script type="text/javascript">
	</script>
	<?php
}

function HTML_back(){
	?>
		<ul>
		<li><input type="button" name="back" value="继续替换" onclick="window.history.go(-1);"></li>
		</ul>
	<?php
}

?>
